<template>
  <div class="container">
    <Breadcrumb :items="['系统管理', '角色管理']" />
    <a-card class="general-card" :title="$t('角色管理')">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            label-align="left"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-layout="inline"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="roleName" :label="$t('角色名称')">
                  <a-input
                    v-model="searchForm.roleName"
                    :placeholder="$t('请输入角色名称')"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="roleKey" :label="$t('权限字符')">
                  <a-input
                    v-model="searchForm.roleKey"
                    :placeholder="$t('请输入权限字符')"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" :label="$t('状态')">
                  <a-select
                    v-model="searchForm.status"
                    :placeholder="$t('请选择状态')"
                    allow-clear
                  >
                    <a-option :value="RoleStatusEnum.ENABLED">正常</a-option>
                    <a-option :value="RoleStatusEnum.DISABLED">停用</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="16">
                <a-space>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ $t('搜索') }}
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    {{ $t('重置') }}
                  </a-button>
                  <a-button
                    type="primary"
                    status="success"
                    @click="openCreateForm"
                  >
                    <template #icon>
                      <icon-plus />
                    </template>
                    {{ $t('新增角色') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-table
        row-key="id"
        :loading="loading"
        :data="renderData"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        :bordered="false"
      >
        <template #columns>
          <a-table-column title="角色名称" data-index="roleName" />
          <a-table-column title="权限字符" data-index="roleKey" />
          <a-table-column title="排序" data-index="roleSort" />
          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              <a-tag
                :color="
                  record.status === RoleStatusEnum.ENABLED ? 'green' : 'red'
                "
              >
                {{ record.statusName || getStatusName(record.status) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="createTime">
            <template #cell="{ record }">
              {{ formatDateTime(record.createTime) }}
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="200">
            <template #cell="{ record }">
              <a-space>
                <a-button
                  type="text"
                  size="small"
                  @click="openEditForm(record)"
                >
                  编辑
                </a-button>
                <a-button
                  type="text"
                  size="small"
                  status="danger"
                  @click="confirmDelete(record)"
                >
                  删除
                </a-button>
                <a-button
                  type="text"
                  size="small"
                  :status="
                    record.status === RoleStatusEnum.ENABLED
                      ? 'danger'
                      : 'success'
                  "
                  @click="toggleStatus(record)"
                >
                  {{
                    record.status === RoleStatusEnum.ENABLED ? '禁用' : '启用'
                  }}
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 角色表单对话框 -->
    <a-modal
      v-model:visible="formVisible"
      :title="formTitle"
      :width="750"
      @before-ok="handleSubmitForm"
      unmount-on-close
    >
      <role-form ref="formRef" :form-data="formData" :is-edit="isEdit" />
      <template #footer>
        <a-space>
          <a-button @click="formVisible = false">取消</a-button>
          <a-button type="primary" @click="submitForm"> 确定 </a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, onMounted } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import dayjs from 'dayjs';
  import {
    IconSearch,
    IconRefresh,
    IconPlus,
  } from '@arco-design/web-vue/es/icon';
  import {
    getRoleList,
    getRoleDetail,
    deleteRole,
    updateRoleStatus,
    Role,
    RoleStatusEnum,
    DataScopeEnum,
    RoleQueryParams,
  } from '@/api/system/role';
  import RoleForm from './components/role-form.vue';

  const { loading, setLoading } = useLoading();
  const renderData = ref<Role[]>([]);
  const formRef = ref();
  const formVisible = ref(false);
  const isEdit = ref(false);
  const formData = ref<Partial<Role>>({});

  // 搜索表单
  const searchForm = reactive<RoleQueryParams>({
    roleName: '',
    roleKey: '',
    status: undefined,
    current: 1,
    size: 10,
  });

  // 分页配置
  const pagination = reactive({
    total: 0,
    current: 1,
    pageSize: 10,
  });

  // 表单标题
  const formTitle = computed(() => {
    return isEdit.value ? '编辑角色' : '新增角色';
  });

  // 格式化日期时间
  function formatDateTime(date: string | undefined) {
    if (!date) return '-';
    return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
  }

  // 获取状态名称
  function getStatusName(status: number | undefined) {
    const statusMap = {
      [RoleStatusEnum.ENABLED]: '正常',
      [RoleStatusEnum.DISABLED]: '停用',
    };
    return status !== undefined
      ? statusMap[status as keyof typeof statusMap]
      : '-';
  }

  // 获取数据范围名称
  function getDataScopeName(dataScope: number | undefined) {
    const dataScopeMap = {
      [DataScopeEnum.ALL]: '全部数据权限',
      [DataScopeEnum.CUSTOM]: '自定数据权限',
      [DataScopeEnum.DEPT]: '本部门数据权限',
      [DataScopeEnum.DEPT_AND_CHILD]: '本部门及以下数据权限',
    };
    return dataScope !== undefined
      ? dataScopeMap[dataScope as keyof typeof dataScopeMap]
      : '-';
  }

  // 查询数据
  async function fetchData() {
    setLoading(true);
    try {
      const params = {
        ...searchForm,
        current: pagination.current,
        size: pagination.pageSize,
      };

      const res = await getRoleList(params);
      renderData.value = res.data.records;
      pagination.total = res.data.total;
    } catch (err) {
      console.error('获取角色列表出错:', err);
      Message.error('获取角色列表失败');
    } finally {
      setLoading(false);
    }
  }

  // 开启新增表单
  function openCreateForm() {
    isEdit.value = false;
    formData.value = {
      roleSort: 0,
      status: RoleStatusEnum.ENABLED,
    };
    formVisible.value = true;
  }

  // 开启编辑表单
  async function openEditForm(record: Role) {
    try {
      const res = await getRoleDetail(record.id);
      formData.value = res.data;
      isEdit.value = true;
      formVisible.value = true;
    } catch (err) {
      console.error('获取角色详情出错:', err);
      Message.error('获取角色详情失败');
    }
  }

  // 确认删除
  function confirmDelete(record: Role) {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除角色 "${record.roleName}" 吗？此操作不可恢复。`,
      onOk: async () => {
        try {
          await deleteRole(record.id);
          Message.success('删除角色成功');
          fetchData();
        } catch (err) {
          console.error('删除角色出错:', err);
          Message.error('删除角色失败');
        }
      },
    });
  }

  // 切换角色状态
  async function toggleStatus(record: Role) {
    const newStatus =
      record.status === RoleStatusEnum.ENABLED
        ? RoleStatusEnum.DISABLED
        : RoleStatusEnum.ENABLED;
    const actionName = newStatus === RoleStatusEnum.ENABLED ? '启用' : '禁用';
    Modal.confirm({
      title: `确认${actionName}`,
      content: `您确定要${actionName}角色 "${record.roleName}" 吗？`,
      onOk: async () => {
        try {
          await updateRoleStatus(record.id, newStatus);
          Message.success(`${actionName}成功`);
          fetchData();
        } catch (err) {
          console.error(`${actionName}角色出错:`, err);
          Message.error(`${actionName}失败`);
        }
      },
    });
  }

  // 提交表单
  async function handleSubmitForm(done: any) {
    try {
      if (!formRef.value) {
        console.error('表单引用不存在');
        Message.error('表单引用不存在');
        done(false);
        return;
      }

      const valid = await formRef.value.validate();

      if (valid) {
        const result = await formRef.value.submit();

        if (result) {
          fetchData();
          done();
        } else {
          done(false);
        }
      } else {
        Message.warning('表单验证未通过，请检查表单内容');
        done(false);
      }
    } catch (err) {
      console.error('提交表单出错:', err);
      Message.error('提交失败');
      done(false);
    }
  }

  // 手动提交表单
  async function submitForm() {
    try {
      if (!formRef.value) {
        Message.error('表单引用不存在');
        return;
      }

      const valid = await formRef.value.validate();

      if (valid) {
        const result = await formRef.value.submit();

        if (result) {
          formVisible.value = false;
          fetchData();
        }
      } else {
        Message.warning('表单验证未通过，请检查表单内容');
      }
    } catch (err) {
      console.error('手动提交出错:', err);
      Message.error('提交失败，请检查表单');
    }
  }

  // 搜索
  function search() {
    pagination.current = 1;
    fetchData();
  }

  // 重置
  function reset() {
    searchForm.roleName = '';
    searchForm.roleKey = '';
    searchForm.status = undefined;
    pagination.current = 1;
    fetchData();
  }

  // 分页变化
  function onPageChange(current: number) {
    pagination.current = current;
    fetchData();
  }

  // 每页条数变化
  function onPageSizeChange(pageSize: number) {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
  }

  // 初始化
  onMounted(() => {
    fetchData();
  });
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  .general-card {
    margin-top: 16px;

    :deep(.arco-card-header) {
      border-bottom: 1px solid var(--color-border-2);
      padding: 16px 20px;
    }
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>
